using System.Text.Json;
using Mathmall.Administration.Mapper;
using Mathmall.Administration.Models;
using Mathmall.Administration.Vo;

namespace Mathmall.Administration.Service.impl;

public class RoleMenuService : IRoleMenuService
{
    private readonly RoleMenuMapper _roleMenuMapper;

    public RoleMenuService(RoleMenuMapper roleMenuMapper)
    {
        _roleMenuMapper = roleMenuMapper;
    }

    /// <summary>
    /// 查询角色已有的权限
    /// </summary>
    /// <param name="roleId"></param>
    /// <returns></returns>
    public async Task<List<int>> GetRolePossessedMenuIds(int roleId)
    {
        List<RoleMenu> roleMenus = await _roleMenuMapper.QueryRolePossessedMenuIds(roleId);
        List<int> menuIds = new List<int>();
        foreach (RoleMenu roleMenu in roleMenus)
        {
            menuIds.Add(roleMenu.MenuId);
        }

        return menuIds;
    }

    /// <summary>
    /// 为角色添加权限
    /// </summary>
    /// <param name="roleMenuVo"></param>
    /// <returns></returns>
    public Task<int> AddRoleMenuAsync(RoleMenuVo roleMenuVo)
    {
        List<RoleMenu> roleMenus = new List<RoleMenu>();
        foreach (int menuId in roleMenuVo.MenuIdList)
        {
            RoleMenu roleMenu = new RoleMenu { RoleId = roleMenuVo.RoleId, MenuId = menuId };
            roleMenus.Add(roleMenu);
        }

        return _roleMenuMapper.CreateRoleMenu(roleMenus);
    }

    /// <summary>
    /// 删除角色对应的权限
    /// </summary>
    /// <param name="roleId"></param>
    /// <returns></returns>
    public async Task<int> DeleteRoleMenu(int roleId)
    {
        return await _roleMenuMapper.DeleteRoleMenu(roleId);
    }
}